package testjava;

public class Endian {

    public static byte[] getBytes(short value) {
        byte[] result = new byte[2];
        result[0] = (byte) ((value >>> 0) & 0xff);
        result[1] = (byte) ((value >>> 8) & 0xff);
        return result;
    }

    public static byte[] getBytes(int value) {
        byte[] result = new byte[4];
        result[0] = (byte) ((value >>> 0) & 0xff);
        result[1] = (byte) ((value >>> 8) & 0xff);
        result[2] = (byte) ((value >>> 16) & 0xff);
        result[3] = (byte) ((value >>> 24) & 0xff);
        return result;
    }

    public static int getInt(byte[] v, int offset) {
        return (toUnsign(v[offset]) << 0) | (toUnsign(v[offset + 1]) << 8) | (toUnsign(v[offset + 2]) << 16) | (toUnsign(v[offset + 3]) << 24);
    }

    public static short getShort(byte[] v, int offset) {
        return (short) ((toUnsign(v[offset]) << 0) | (toUnsign(v[offset + 1]) << 8));
    }

    public static int toUnsign(byte v) {
        return v & 0xFF;
    }
    
    public static int toUnsign(short v) {
        return v & 0xFFFF;
    }

}
